import os
import sys

from PyQt5.QtWidgets import QWidget, QLabel, QHBoxLayout, QVBoxLayout, QPushButton, QTextEdit, QTableWidget, QTableWidgetItem, QCheckBox, QGridLayout, QApplication, QHeaderView
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QFont

import time, threading

class TransactionDetial(QWidget):

    code_list = []
    right_list = []
    right_botton_list = []
    stop_time = False
    t = ''
    status = ''
    has_fresh = False
    loop_start = True

    def cycle_post(self):
        # FIXME: timeout结束线程 正常结束
        print("-------------------------------------------进入线程")
        self.t = threading.Thread(target=self.loop, name='LoopThread')
        self.t.start()
        print("退出线程-------------------------------------------")

    def loop(self):
        while self.loop_start:
            if not self.is_stop_cycle:
                is_break, sleep_time = self._cycle_post()
                # if is_fresh:
                    # self.freshDataTimer()
                if is_break:
                    # TODO: 11次 炸了 这里可以通知界面
                    self.loop_start = False
                else:
                    print('开始睡觉%s'%sleep_time)
                    time.sleep(sleep_time)
            else:
                print('停止交易')

    def _cycle_post(self):
        # rule_list checkbox选择列表
        print('界面调用开奖结果')
        serial, number_list = self.car._get_lottery_res()

        self.has_fresh = False  # 是否更新了数据

        # # 更新左下数据
        print('更新左下数据')
        history_number_list = self.car.set_history_data()
        self.code_list = []
        for code, value in history_number_list.items():
            number = ''
            for i in value[0]:
                number += str(i)
            self.code_list.append({'code': code, 'number': number, 'money': value[1]})
        # self.freshLeftDom()

        # TODO: 走后端时间控制
        left_time, left_second = self.car.get_left_time()
        self.prefit2 = self.car.win_money
        if left_time and left_second - 10 > 0:  # 还没有封盘，并且剩余时间大于10秒 下单
            print('界面进入下单')
            lost, rule_list, msg_list = self.car.follow_rules(self.rule_list)
            # 更新右上盈利
            print('更新右上盈利')
            print(rule_list)
            self.prefit = 0
            for index, rule in enumerate(rule_list):
                self.right_list[index]['prefit'] = rule[4]
                self.prefit = self.prefit+float(rule[4])
            # self.freshRightTop()
                print(rule[4])
            if lost:
                self.status = True
                return True, 0

            for msg in msg_list:
                msg = msg.split(',')
                self.right_botton_list.append(
                    {'qihao': msg[0], 'code': msg[1], 'position': msg[2], 'number': msg[3], 'money': '',
                     'one': msg[4], 'count': msg[5], 'state': '1', 'open': '', 'caculate': '', 'mode': ''})
                # self.freshDataTimer()
                self.has_fresh = True  # 更新了数据
                print(self.right_botton_list)

        # for rule in self.rule_list:
        #     left_time, left_second = self.car.get_left_time()
        #     self.prefit2 = self.car.win_money
        #     if left_time and left_second - 10 > 0:  # 还没有封盘，并且剩余时间大于10秒 下单
        #         print('界面开始下单')
        #         msg = self.car.follow_rule(rule, serial)
        #         # 右下insert msg
        #         # 703697,2,10,[3, 7, 8, 9, 0],3,1
        #         msg = msg.split(',')
        #         self.right_botton_list.append(
        #             {'qihao': msg[0], 'code': msg[1], 'position': msg[2], 'number': msg[3], 'money': '',
        #              'one': msg[4], 'count': msg[5], 'state': '1', 'open': '', 'caculate': '', 'mode': ''})
        #         # self.freshDataTimer()
        #         self.has_fresh = True  # 更新了数据
        #         print(self.right_botton_list)
        #
        #     else:  # 已经封盘了过left_second+2后开始下单
        #         break
        left_time, left_second = self.car.get_left_time()
        if left_time:
            self.signalSecond = left_second + 55  # 设置下次运行的时间
        else:
            self.signalSecond = left_second + 25  # 设置下次运行的时间
        self.status = False
        print('准备下次循环')
        self.update()
        return False, self.signalSecond

    def __init__(self, the_code, username, password, key):
        try:
            super(TransactionDetial, self).__init__()
            print('1111111111')
            self.car = carSpider(the_code, username, password, key)
            self.car.set_history_data()
            self.rule_list=[]
            self.right_list_msg=[]
            self.prefit = 0.0
            self.prefit2 = 0.0
            self.is_stop_cycle = False
        except Exception as exc:
            print(exc)
        history_number_list = self.car.history_number_list
        for code, value in history_number_list.items():
            number = ''
            for i in value[0]:
                number += str(i)
            self.code_list.append({'code': code, 'number': number, 'money': value[1]})
        print(self.code_list)

        origin_rule_list = self.car.origin_rule_list
        for code, rule in enumerate(origin_rule_list):
            print(rule[0], rule[1], rule[2])
            self.right_list.append({'code':code, 'state':'ok', 'ball_number':rule[0], 'number':rule[1], 'prefit':'0', 'beitou': rule[2], 'check': 0})
            self.rule_list.append(int(code))
        self.right_botton_list=[]

        self.main_layuot = QHBoxLayout()
        self.left_layout = QVBoxLayout()
        self.right_layout = QVBoxLayout()
        self.main_layuot.setContentsMargins(10, 10, 10, 10)

        self.initUserInfo()
        self.initRightTable()
        self.initLeftTable()
        self.initRightBottonTable()
        self.main_layuot.addLayout(self.left_layout,3)
        self.main_layuot.addLayout(self.right_layout,10)
        self.setLayout(self.main_layuot)
        self.signalSecond = 10000
        self.showMaximized()
        # self.timer = QTimer(self)  # 初始化一个定时器
        # self.timer.timeout.connect(self.freshDataTimer)


    def initUserInfo(self):
        self.user_grid_layout = QGridLayout()

        self.account_lb = QLabel("账号：（123456）")
        self.account_lb.setFont(QFont("song", 9, QFont.Bold))

        self.maney_lb = QLabel("余额：（55555000）")
        self.maney_lb.setFont(QFont("song", 9, QFont.Bold))

        self.liushui_lb = QLabel("流水：500")
        self.liushui_lb.setFont(QFont("song", 9, QFont.Bold))

        self.yingk_lb = QLabel("盈亏：500")
        self.yingk_lb.setFont(QFont("song", 9, QFont.Bold))

        self.time_lb = QLabel("延时 0 秒后开始下注")
        self.time_lb.setFont(QFont("song", 9, QFont.Bold))

        self.zhiying_qhl = QHBoxLayout()
        self.zhikui_qhl = QHBoxLayout()
        yingk_qhl = QHBoxLayout()

        zhiying_lb = QLabel("止盈")
        self.zhiying_qte = QTextEdit()
        self.zhiying_qte.setFixedHeight(27)
        self.zhiying_qte.setFixedWidth(80)
        self.zhiying_qhl.addWidget(zhiying_lb)
        self.zhiying_qhl.addWidget(self.zhiying_qte)
        self.zhiying_qhl.setSpacing(0)

        zhikui_lb = QLabel("止亏")
        self.zhikui_qte = QTextEdit()
        self.zhikui_qte.setFixedHeight(27)
        self.zhikui_qte.setFixedWidth(80)


        self.zhikui_qhl.addWidget(zhikui_lb)
        self.zhikui_qhl.addWidget(self.zhikui_qte)
        self.zhikui_qhl.setSpacing(0)

        yingk_qhl.addLayout(self.zhiying_qhl)
        yingk_qhl.addLayout(self.zhikui_qhl)
        yingk_qhl.setSpacing(60)


        self.user_grid_layout.addWidget(self.account_lb, 0, 0, 1, 1)
        self.user_grid_layout.addWidget(self.maney_lb, 0, 1, 1, 1)
        self.user_grid_layout.addWidget(self.liushui_lb, 1, 0, 1, 1)
        self.user_grid_layout.addWidget(self.yingk_lb, 1, 1, 1, 1)
        self.user_grid_layout.addWidget(self.time_lb, 2, 0, 1, 1)

        bottomHbox = QHBoxLayout()
        bottomHbox.setSpacing(5)

        self.gj_btn = QPushButton("挂机")
        self.gj_btn.setFixedWidth(80)
        self.gj_btn.setStyleSheet(
            "QWidget{ background:#169bef;color: white;font-size:18px;border: 1px solid white;font-weight: bold;border-width: 0px;border-color: #141529;border-style: solid;border-radius:5;}")
        self.gj_btn.clicked.connect(self.start_cycle)
        self.tz_btn = QPushButton("停止")
        self.tz_btn.setFixedWidth(80)
        self.tz_btn.setStyleSheet(
            "QWidget{ background:#169bef;color: white;font-size:18px;border: 1px solid white;font-weight: bold;border-width: 0px;border-color: #141529;border-style: solid;border-radius:5;}")
        self.tz_btn.clicked.connect(self.stop_cycle)
        bottomHbox.addWidget(self.gj_btn)
        bottomHbox.addWidget(self.tz_btn)

        self.user_main = QVBoxLayout()
        self.user_main.addLayout(self.user_grid_layout)
        self.user_main.addLayout(yingk_qhl)
        self.user_main.addLayout(bottomHbox)
        self.left_layout.addLayout(self.user_main,1)

    def start_cycle(self):
        # 启动线程
        self.is_stop_cycle = False
        self.loop_start = True
        self.gj_btn.setEnabled(False)
        self.gj_btn.setStyleSheet(
            "QWidget{ background:#D1D1D1;color: white;font-size:18px;border: 1px solid white;font-weight: bold;border-width: 0px;border-color: #141529;border-style: solid;border-radius:5;}")
        self.cycle_post()

    def stop_cycle(self):
        # 结束线程
        self.is_stop_cycle = True
        self.loop_start = False
        self.gj_btn.setEnabled(True)
        self.gj_btn.setStyleSheet(
            "QWidget{ background:#169bef;color: white;font-size:18px;border: 1px solid white;font-weight: bold;border-width: 0px;border-color: #141529;border-style: solid;border-radius:5;}")
        # TODO: 最后一次不下单的话 中奖判断
        # 获取时间 启线程 获取开奖结果 如果 start 被启动 这个线程再见
        self.th_last_winning()

    def th_last_winning(self):
        print("-------------------------------------------进入last线程")
        self.t = threading.Thread(target=self.last_winning, name='LoopThread')
        self.t.start()
        print("退出last线程-------------------------------------------")

    def last_winning(self):
        # 最后一次不下单的话 中奖判断
        left_time, left_second = self.car.get_left_time()
        if left_time:
            signalSecond = left_second + 55  # 设置下次运行的时间
        else:
            signalSecond = left_second + 25  # 设置下次运行的时间
        time.sleep(signalSecond)
        if not self.loop_start:
            rule_list = self.car.adjust_winning(self.rule_list)
            print('更新右上盈利')
            print(rule_list)
            self.prefit = 0
            for index, rule in enumerate(rule_list):
                self.right_list[index]['prefit'] = rule[4]
                self.prefit = self.prefit+float(rule[4])
                # print(rule[4])

    def paintEvent(self, e):
        self.freshDataTimer()
        self.freshRightTop()
        self.updateLeftTop()
        self.freshLeftDom()

    def updateLeftTop(self):
        self.yingk_lb.setText('盈亏：'+str(self.prefit)+":"+str(self.prefit2))

    def initLeftTable(self):

        self.stockDetailList = QTableWidget()  # '期号', '号码', '余额'
        stockDetaihorizontalHeader = ['期号', '号码', '余额']
        self.LeftTableHeaderCode = ['code', 'number', 'money']
        self.stockDetailList.setColumnCount(len(stockDetaihorizontalHeader))
        self.stockDetailList.setRowCount(len(self.code_list))
        self.stockDetailList.setHorizontalHeaderLabels(stockDetaihorizontalHeader)
        self.stockDetailList.verticalHeader().setVisible(False)  # 隐藏垂直表头

        self.stockDetailList.setEditTriggers(QTableWidget.NoEditTriggers)
        # self.stockDetailList.setSelectionBehavior(QTableWidget.SelectRows)
        self.stockDetailList.setSelectionMode(QTableWidget.SingleSelection)
        for tmp_table_row in range(self.stockDetailList.rowCount()):
            for tmp_columncount  in range(self.stockDetailList.columnCount()):
                self.stockDetailList.setRowHeight(tmp_table_row, 25)
                item = QTableWidgetItem(str(self.code_list[tmp_table_row][self.LeftTableHeaderCode[tmp_columncount]]))
                item.setTextAlignment(Qt.AlignCenter)
                self.stockDetailList.setItem(tmp_table_row,tmp_columncount, item)

        self.layout3 = QHBoxLayout()
        self.layout3.setAlignment(Qt.AlignVCenter)  # 垂直居中
        self.layout3.setContentsMargins(0, 0, 0, 0)
        self.layout3.addWidget(self.stockDetailList)
        self.left_layout.addLayout(self.layout3,3)

    def initRightTable(self):
        self.right_top_list_view = QTableWidget()
        stockDetaihorizontalHeader = ['编号', '状态', '球号', '号码', '盈亏', '倍投']
        self.right_topHeaderCode = ['code', 'state', 'ball_number', 'number', 'prefit', 'beitou']
        self.right_top_list_view.setColumnCount(len(stockDetaihorizontalHeader))
        self.right_top_list_view.setRowCount(len(self.right_list))
        self.right_top_list_view.setHorizontalHeaderLabels(stockDetaihorizontalHeader)
        self.right_top_list_view.verticalHeader().setVisible(False)  # 隐藏垂直表头

        self.right_top_list_view.setEditTriggers(QTableWidget.NoEditTriggers)
        # self.stockDetailList.setSelectionBehavior(QTableWidget.SelectRows)
        self.right_top_list_view.setSelectionMode(QTableWidget.SingleSelection)
        for tmp_table_row in range(self.right_top_list_view.rowCount()):
            for tmp_columncount in range(self.right_top_list_view.columnCount()):
                self.right_top_list_view.setRowHeight(tmp_table_row, 25)
                tmp_widget = QWidget()
                tmpLayout = QHBoxLayout()
                if tmp_columncount == 1:
                    check = int(self.right_list[tmp_table_row].get('check',1))
                    cb_btn = MyCheckBox()
                    tmpLayout.addWidget(cb_btn)
                    cb_btn.setrowNo(tmp_table_row)
                    cb_btn.clicked.connect(self.changeTitle)
                    if check == 0:
                        cb_btn.setChecked(True)
                    else:
                        cb_btn.setChecked(False)
                    tmpLayout.setAlignment(Qt.AlignHCenter)
                    tmpLayout.setContentsMargins(0, 0, 0, 0)
                    tmp_widget.setLayout(tmpLayout)
                    self.right_top_list_view.setCellWidget(tmp_table_row, tmp_columncount, tmp_widget)
                else:
                    item = QTableWidgetItem(
                        str(self.right_list[tmp_table_row][self.right_topHeaderCode[tmp_columncount]]))
                    item.setTextAlignment(Qt.AlignCenter)
                    self.right_top_list_view.setItem(tmp_table_row, tmp_columncount, item)
        header = self.right_top_list_view.horizontalHeader()
        header.setSectionResizeMode(5, QHeaderView.ResizeToContents)

        layout3 = QHBoxLayout()
        layout3.setAlignment(Qt.AlignVCenter)  # 垂直居中
        layout3.setContentsMargins(0, 0, 0, 0)
        layout3.addWidget(self.right_top_list_view)
        self.right_layout.addLayout(layout3,1)

    def changeTitle(self, state):
        rowNo = self.sender().getrowNo()
        info = self.right_list[rowNo]
        code = int(self.right_list[rowNo]['code'])
        if state:
            if code not in self.rule_list:
                self.rule_list.append(code)
            info['check'] = 0
            print('选择到了')
        else:
            if code in self.rule_list:
                self.rule_list.remove(code)
            print('没有选择')
            info['check'] = 1
        print(self.rule_list)

    def initRightBottonTable(self):
        self.right_bom_list_view = QTableWidget()
        stockDetaihorizontalHeader = ['期号', '编号', '位置', '号码', '资金', '单注', '手数','投注状态', '开奖', '结算', '方案模式']
        self.stockDetaihorizontalHeaderCode = ['qihao', 'code', 'position', 'number', 'money', 'one', 'count','state','open','caculate', 'mode']
        self.right_bom_list_view.setColumnCount(len(stockDetaihorizontalHeader))
        self.right_bom_list_view.setRowCount(len(self.right_botton_list))
        self.right_bom_list_view.setHorizontalHeaderLabels(stockDetaihorizontalHeader)
        self.right_bom_list_view.verticalHeader().setVisible(False)  # 隐藏垂直表头

        self.right_bom_list_view.setEditTriggers(QTableWidget.NoEditTriggers)
        self.right_bom_list_view.setSelectionMode(QTableWidget.SingleSelection)
        for tmp_table_row in range(self.right_bom_list_view.rowCount()):
            for tmp_columncount in range(self.right_bom_list_view.columnCount()):
                self.right_bom_list_view.setRowHeight(tmp_table_row, 25)
                item = QTableWidgetItem(
                    str(self.right_botton_list[tmp_table_row][self.stockDetaihorizontalHeaderCode[tmp_columncount]]))
                item.setTextAlignment(Qt.AlignCenter)
                self.right_bom_list_view.setItem(tmp_table_row, tmp_columncount, item)

        layout3 = QHBoxLayout()
        layout3.setAlignment(Qt.AlignVCenter)  # 垂直居中
        layout3.setContentsMargins(0, 0, 0, 0)
        layout3.addWidget(self.right_bom_list_view)
        self.right_layout.addLayout(layout3,2)

    # 定时刷新数据界面
    def freshDataTimer(self):

        self.right_bom_list_view.clearContents()
        self.update_left_bottom_view()

    def freshLeftDom(self):
        """
        刷新左下
        :return:
        """
        self.stockDetailList.clearContents()
        self.stockDetailList.setRowCount(len(self.code_list))
        for tmp_table_row in range(self.stockDetailList.rowCount()):
            for tmp_columncount  in range(self.stockDetailList.columnCount()):
                self.stockDetailList.setRowHeight(tmp_table_row, 25)
                item = QTableWidgetItem(str(self.code_list[tmp_table_row][self.LeftTableHeaderCode[tmp_columncount]]))
                item.setTextAlignment(Qt.AlignCenter)
                self.stockDetailList.setItem(tmp_table_row,tmp_columncount, item)

    def freshRightTop(self):
        """
        刷新右上
        :return:
        """
        # self.right_top_list_view.clearContents()
        # self.right_top_list_view.setRowCount(len(self.right_list))
        for tmp_table_row in range(self.right_top_list_view.rowCount()):
            for tmp_columncount in range(self.right_top_list_view.columnCount()):
                if tmp_columncount == 5:
                    self.right_top_list_view.item(tmp_table_row, tmp_columncount).\
                        setText(str(self.right_list[tmp_table_row][self.right_topHeaderCode[tmp_columncount]]))
                # self.right_top_list_view.setRowHeight(tmp_table_row, 25)
                # self.tmp_widget = QWidget()
                # self.tmpLayout = QHBoxLayout()
                # if tmp_columncount == 1:
                #     check = int(self.right_list[tmp_table_row].get('check', 1))
                #     cb_btn = MyCheckBox()
                #     self.tmpLayout.addWidget(cb_btn)
                #     cb_btn.setrowNo(tmp_table_row)
                #     cb_btn.clicked.connect(self.changeTitle)
                #     if check == 0:
                #         cb_btn.setChecked(True)
                #     else:
                #         cb_btn.setChecked(False)
                #     self.tmpLayout.setAlignment(Qt.AlignHCenter)
                #     self.tmpLayout.setContentsMargins(0, 0, 0, 0)
                #     self.tmp_widget.setLayout(self.tmpLayout)
                #     self.right_top_list_view.setCellWidget(tmp_table_row, tmp_columncount, self.tmp_widget)
                # else:
                #     item = QTableWidgetItem(
                #         str(self.right_list[tmp_table_row][self.right_topHeaderCode[tmp_columncount]]))
                #     item.setTextAlignment(Qt.AlignCenter)
                #     self.right_top_list_view.setItem(tmp_table_row, tmp_columncount, item)
        # header = self.right_top_list_view.horizontalHeader()
        # header.setSectionResizeMode(6, QHeaderView.ResizeToContents)

    def update_left_bottom_view(self):
        # print( str(len(self.right_botton_list)) + '：：数据长度' )
        self.right_bom_list_view.setRowCount(len(self.right_botton_list))
        for tmp_table_row in range(self.right_bom_list_view.rowCount()):
            # print(str(tmp_table_row)+ '行号：：：：')
            for tmp_columncount in range(self.right_bom_list_view.columnCount()):
                self.right_bom_list_view.setRowHeight(tmp_table_row, 25)
                item = QTableWidgetItem(
                    str(self.right_botton_list[tmp_table_row][self.stockDetaihorizontalHeaderCode[tmp_columncount]]))
                item.setTextAlignment(Qt.AlignCenter)
                self.right_bom_list_view.setItem(tmp_table_row, tmp_columncount, item)

class MyCheckBox(QCheckBox):
    """
    交易列表详情按钮控件
    """
    def __init__(self):
        super(MyCheckBox, self).__init__()
        self.rowNo = 0

    def setParentWidget(self, parentWidget):
        self.parentWidget = parentWidget

    def setrowNo(self, rowNo):
        self.rowNo = rowNo

    def getrowNo(self):
        return self.rowNo


# -*- coding: utf-8 -*-
# © 2018 QYT Technology
import time
# import pickle
import os, re
from collections import OrderedDict
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from retrying import retry
import datetime
import configparser

class carSpider():
    history_number_list = OrderedDict()  # 左下历史记录
    number_list = []
    browser = ''
    # rule_dict = {
    #     1: ['ball', ['follow_list'], ['value_list'], 'times', 'left'],
    # }
    origin_rule_list = []
    rule_list = []
    record_list = []
    add_record_list = []
    record = {}  # 用来计算中奖 其实好像没什么用 就是用来判断第一次中奖
    win_money = 0
    is_repeat = 0

    @retry
    def get_server(self, the_code):
        browser = webdriver.Chrome(path)
        browser.get(url)
        time.sleep(2)
        elem_code = browser.find_element_by_id('code')
        elem_code.send_keys(the_code)
        commit = browser.find_element_by_xpath('/html/body/form/div[2]/div[2]/input')
        commit.click()
        time.sleep(2)

        line_choice = browser.find_element_by_xpath('/html/body/div[3]/div/div[2]/table/tbody/tr/td[1]/a')
        link = line_choice.get_attribute("href")
        browser.get(link)
        time.sleep(2)
        return browser

    def __init__(self, the_code, username, password, key):
        ######直接初始化到赛车页面
        print(2222222)
        # self.read_record()  # 可以单独调用
        self.read_rule()
        self.browser = self.get_server(the_code)
        self.login(username, password)
        self.xxxxx()
        self.agree()
        self.car_menu()
        # self.get_lottery_res()

    @retry
    def login(self, username, password):
        loginName = self.browser.find_element_by_id('loginName')
        loginName.send_keys(username)
        loginPwd = self.browser.find_element_by_id('loginPwd')
        loginPwd.send_keys(password)
        commit = self.browser.find_element_by_id('login_btn')
        time.sleep(2)
        commit.click()

    @retry
    def xxxxx(self):
        time.sleep(2)
        xxxxx = self.browser.find_element_by_xpath('//*[@id="myLayer_19841012"]/tbody/tr/td/div[1]/a')
        xxxxx.click()
        return True

    @retry
    def agree(self):
        agree = self.browser.find_element_by_xpath('/html/body/div[1]/div/div[3]/input[2]')
        agree.click()
        return True

    @retry
    def car_menu(self):
        # 要刷数据的时候先调用 FIXME: 这里经常切换不到
        time.sleep(2)
        print('切换到汽车')
        self.browser.switch_to.default_content()
        menu = self.browser.find_element_by_id("menuText")
        car = self.browser.find_element_by_xpath('//*[@id="menuList"]/li[3]/a')
        ActionChains(self.browser).move_to_element(menu).click(car).perform()
        return True

    ###############下面是各种获取数据
    @retry
    def _get_lottery_res(self):
        # 获取开奖结果
        print('获取开奖结果')
        time.sleep(2)
        try:
            self.browser.switch_to.frame("mainIframe")  # 切换到iframe
        except:
            pass
        now_number = self.browser.find_element_by_id('NowJq').text  # 当前期数
        number = self.browser.find_element_by_id('newPhase').text  # 期数
        while int(now_number) - int(number) > 1:
            now_number = self.browser.find_element_by_id('NowJq').text  # 当前期数
            number = self.browser.find_element_by_id('newPhase').text  # 期数
            time.sleep(2)
        self.number_list = []
        for i in range(1, 11):
            value = int(self.browser.find_element_by_xpath(
                '//*[@id="prevBall"]/span[%d]' % (i)).get_attribute("class").split('_')[1])
            if int(value) == 10:
                value = 0
            self.number_list.append(value)
        print(self.number_list)
        return number, self.number_list


    def get_lottery_res(self, date_time='2018-08-08'):
        """for test"""
        history_list = self.read_history(date_time)
        history_list.reverse()
        self.history_ger = (i for i in history_list)
        return self.history_ger

    def test_lottery_res(self):
        """for test"""
        history = self.history_ger.__next__()
        history = history.split(',')
        if '-------' not in history[1]:
            number = int(history[1])
            self.number_list = [int(i) for i in history[2].strip('\n')]
        print('--------------------------%s,%s'%(number, str(self.number_list)))
        return number, self.number_list

    def get_left_money(self):
        """
        获取余额
        """
        self.browser.switch_to.default_content()  # 切回
        self.left_money = self.browser.find_element_by_id('usableCreditSpan').text  # 可用余额
        return self.left_money

    @retry
    def get_left_time(self):
        """
        获取当前剩余时间
        :return:
        """
        print('获取剩余时间')
        try:
            self.browser.switch_to.frame("mainIframe")  # 切换到iframe
        except:
            pass
        text = self.browser.find_element_by_id('closeText').text
        self.win_money = self.browser.find_element_by_id('profit').text  # 今日输赢
        close_time = self.browser.find_element_by_id('closedTime').text  # 剩余时间
        close_time = re.findall('(\d{2})分(\d*)秒', close_time)
        left_second = int(close_time[0][0]) * 60 + int(close_time[0][1])
        print('剩余时间%s'%left_second)
        if text == '封盤':
            return True, left_second
        else:
            return False, left_second

    @retry
    def set_history_data(self):
        self.car_menu()
        time.sleep(2)
        number, number_list = self._get_lottery_res()
        left_money = self.get_left_money()
        if number not in self.history_number_list:
            self.history_number_list[number] = (number_list, left_money)
        print(self.history_number_list)
        return self.history_number_list

    @retry
    def switch_car_iframe(self):
        # 切换到赛车 单球投注页
        print('切换到单球投注页')
        try:
            self.browser.switch_to.frame("mainIframe")  # 切换到iframe
        except:
            pass
        single_ball = self.browser.find_element_by_xpath('/html/body/div[2]/div[2]/div[1]/div[1]/div/div[1]/ul/li[2]/a')
        single_ball.click()
        time.sleep(3)

    @classmethod
    def _inw_axis(self):
        # 投注框坐标 第七名是 序列规则改变
        # 1 5 9 13 17 21 24  27 30 33
        # 1-10 17-26 33-42
        axis = {}
        y_axis = []
        n = 1
        for _ in range(0, 6):
            tmp = []
            for i in range(n, n+10):
                tmp.append(i)
            y_axis.append(tmp)
            n += 16

        n = 95
        for _ in range(0, 4):
            tmp = []
            for i in range(n, n+10):
                tmp.append(i)
            y_axis.append(tmp)
            n += 14

        for n, i in enumerate(range(1, 22, 4)):
            axis[i] = y_axis[n]
        for n, i in enumerate(range(24, 34, 3)):
            axis[i] = y_axis[n+6]
        return axis

    def _generate_inw(self, x, y):
        """
        :param x: 名次 不用-1 获取名次时已经减了
        :param y: 号码
        """
        y -= 1
        x = [1, 5, 9, 13, 17, 21, 24, 27, 30, 33][x]
        axis = self._inw_axis()
        return (x, axis[x][y])

    def _set_amount(self, x, y, value):
        # 设置投注金额
        axis = self._generate_inw(x, y)
        input = self.browser.find_element_by_xpath('//*[@id="inw_%d_%d"]/input'%axis)
        input.send_keys(value)

    # @classmethod
    # def add_rule(cls, serial, ball, follow_list, value_list):
    #     cls.rule_dict[serial] = [ball, follow_list, value_list, 1, 0]
    #     cls.save_rule()

    # @classmethod
    # def save_rule(cls):
    #     with open(cls.rule_file, 'wb') as f:
    #         pickle.dump(cls.rule_dict, f)
    #
    # def read_rule(self):
    #     """
    #     初始化规则
    #     """
    #     try:
    #         with open(self.rule_file, 'rb') as f:
    #             self.rule_dict = pickle.load(f)
    #         return self.rule_dict
    #     except IOError:
    #         pass
    # TODO: 是否可以保存每次记录

    def read_rule(self):
        """
        初始化规则
        """
        try:
            print(3333)
            print(rule_file)
            with open(rule_file, 'r') as f:
                rule_list = f.readlines()
                for rule in rule_list:
                    rule = rule.split('\n')[0]
                    if rule:
                        rule = rule.split('|')
                        print(rule)
                        self.value_count = len(rule[2].split('-'))
                        self.origin_rule_list.append([rule[0], rule[1], rule[2]])
                        self.rule_list.append([int(rule[0]), [int(i) for i in rule[1]], rule[2].split('-'), 0, 0])
            return self.rule_list
        except IOError:
            pass

    def add_record(self, data):
        """
        add_record("dd, sada,1 ,1312")
        """
        data = str(data) + '\r\n'
        with open(record_file, 'a') as f:
            f.writelines(data)

    def add_rule_record(self, data, date_time):
        """
        add_record("dd, sada,1 ,1312")
        """
        data = str(data) + '\r\n'
        record_file = os.path.join(os.path.curdir, '%s_%s_rule_record.txt'%(date_time, self.value_count))

        with open(record_file, 'w') as f:
            f.writelines(data)

    @classmethod
    def read_record(cls):
        """
        初始化记录，可以先读
        record[:-1].split(',')
        """
        try:
            with open(record_file, 'r') as f:
                cls.record_list = f.readlines()
                return cls.record_list
        except IOError:
            pass

    def follow_rules(self, target_rule_list):
        """
        :param target_rule_list: 需要执行的规则序列号 这里的编号从0开始
        :return:
        """
        # target_rule_list = [i for i in range(100)]
        number, number_list = self._get_lottery_res()  # 期数，开奖号码
        self.add_record_list = []
        stop = False
        if self.is_repeat == int(number):  # 已经下过单
            return stop, self.rule_list, []
        for rule_serial in target_rule_list:
            self._adjust_winning(rule_serial, self.rule_list[rule_serial])
        add_record_list = []
        try:
            self.adjust_times()  # 有规则超过11次
            rule_list = [self.rule_list[rule_serial] for rule_serial in target_rule_list]
            sum_rule_dict = self.sum_rule(rule_list)

            # if self.get_left_time():  # 如果没时间了 停止投注 目前前端判断
            #     return
            self.switch_car_iframe()
            count_v = 0
            for key, value in sum_rule_dict.items():
                rank = self.number_list.index(key)  # 名次x坐标
                for y,v in value.items():
                    count_v += v
                    self._set_amount(rank, y, v)
            print("本次投注: %s"%count_v)  # 本次投注金额
            submit = self.browser.find_element_by_id('gameSubmit')
            # submit.click()
            time.sleep(1)
            # submit2 = self.browser.find_element_by_xpath('//*[@id="myLayer_19841012"]/tbody/tr/td/div[3]/a[2]')
            # submit2.click()
            # 避免重复下单
            self.is_repeat = int(number)

            # 返回流水
            for rule_serial in target_rule_list:
                rule = self.rule_list[rule_serial]
                self.sub_value(rule)
                rank = self.number_list.index(rule[0])  # 名次x坐标
                value = int(rule[2][rule[3]-1])  # sub_value的时候把次数加一了，这里要取上次
                self.add_record("%s,%s,%s,%s,%s,%s" % (int(number) + 1, rule_serial, rank + 1, self.list_to_str(rule[1]),
                                                       value, rule[3]))  # 期号，规则序号(是否加1), 位置, 投注球, 金额, 手数
                add_record_list.append("%s,%s,%s,%s,%s,%s"%(int(number) + 1, rule_serial, rank + 1,
                                                            self.list_to_str(rule[1]), value, rule[3]))
                self.record[rule_serial] = [rank, rule[3]]
        except Exception as e:
            print(e)
            stop = True
        data = ''
        for t in self.rule_list:
            data = data + str(t) + '\r\n'
        print(data)
        today = datetime.datetime.today()
        self.add_rule_record(data, today.strftime('%Y-%m-%d'))
        return stop, self.rule_list, add_record_list

    def list_to_str(self, enter_list):
        target_str = ''
        for i in enter_list:
            target_str += str(i)
        return target_str

    def sum_rule(self, rule_list):
        """
        整合投注
        :return:
        """
        rule_dict = {}
        for rule in rule_list:
            target_number = rule[0]
            target_rule = rule[1]
            value = int(rule[2][rule[3]])
            number_value_dict = {}

            exist_number_value_dict = rule_dict.get(target_number)
            if exist_number_value_dict:
                for index in target_rule:
                    count_value = exist_number_value_dict.get(index)
                    if count_value:
                        exist_number_value_dict[index] += value
                    else:
                        exist_number_value_dict[index] = value
            else:
                for index in target_rule:
                    number_value_dict[index] = value
                rule_dict[rule[0]] = number_value_dict
        return rule_dict

    # def follow_rule(self, rule_serial, number):
    #     print('开始投注')
    #     # self._adjust_winning(rule_serial, self.rule_list[rule_serial])
    #     return self._follow_rule(rule_serial, self.rule_list[rule_serial], number)

    def adjust_winning(self, target_rule_list):
        """
        刷规则盈利
        """
        print('刷规则盈利')
        self._get_lottery_res()  # 期数，开奖号码
        for rule_serial in target_rule_list:
            self._adjust_winning(rule_serial, self.rule_list[rule_serial])
            data = ''
            for t in self.rule_list:
                data = data + str(t) + '\r\n'
            print(data)
            today = datetime.datetime.today()
            self.add_rule_record(data, today.strftime('%Y-%m-%d'))
        return self.rule_list

    def adjust_times(self):
        for rule in self.rule_list:
            if rule[3] > self.value_count - 1:# 任意一条规则 12次表示认输 一切停止
                print("超过%s次"%self.value_count)
                raise Exception

    def sub_value(self, rule):
        """
        投注后减去本次成本
        """
        value = rule[2][rule[3]]  # 本次投注金额
        rule[4] = round(rule[4] - int(value) * 5, 2)  # 先扣掉投注的资金
        rule[3] += 1  # 次数+1

    def _adjust_winning(self, serial, rule):  # TODO: 加入期号判断
        """
        是否中奖
        ['ball', ['follow_list'], ['value_list'], 'times', 'left']
        :return:
        """
        if serial in self.record:  # 第一次是空的
            rank = self.record[serial][0]
            win_number = self.number_list[rank]
            value = rule[2][rule[3]-1]  # 上次投注金额 已经被+1
            if win_number in rule[1]:
                self.record[serial][1] = 0  # 重置次数
                rule[3] = 0
                rule[4] = round(rule[4] + int(value) * peilv, 2)

    def return_content(self):
        self.browser.switch_to.default_content()  # 切回

    def read_history(self, date_time):
        history_file = os.path.join(os.path.curdir, '%shistory.txt'%date_time)
        with open(history_file, 'r') as f:
            return f.readlines()


path = os.path.join(os.getcwd(), 'chromedriver.exe')

config = configparser.ConfigParser()
config_ini = os.path.join(os.getcwd(), 'config1.ini')

config.read(config_ini)
config.items('DEFAULT')
url = config['DEFAULT']['url']
# code = config['DEFAULT']['code']
# username = config['DEFAULT']['username']
# password = config['DEFAULT']['password']
line = int(config['DEFAULT']['line'])
peilv = float(config['DEFAULT']['peilv'])
rule_file = os.path.join(os.getcwd(), 'rule.txt')
record_file = os.path.join(os.getcwd(), 'record.csv')
number_result = os.path.join(os.getcwd(), 'number.csv')

# 登陆界面
from PyQt5.QtWidgets import QWidget, QLabel, QHBoxLayout, QVBoxLayout, QPushButton, QTextEdit, QTableWidget, QTableWidgetItem, QCheckBox, QGridLayout, QApplication, QHeaderView,QLineEdit
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QFont
import threading
import sys
import os
class LoginFrom(QWidget):
    def __init__(self):
        super(LoginFrom, self).__init__()

        self.initUI()

    def initUI(self):
        self.setWindowTitle("登录")
        self.setAutoFillBackground(False)
        self.setWindowFlags(Qt.WindowMinimizeButtonHint| Qt.WindowCloseButtonHint|Qt.MSWindowsFixedSizeDialogHint)
        self.setGeometry(500,200,300,300)
        #窗口垂直布局
        vbox = QVBoxLayout()
        vbox.setSpacing(0)
        self.setLayout(vbox)
        Lab = QLabel("用户登录")
        Lab.setFixedHeight(20)
        Lab.adjustSize()
        Lab.setFont(QFont("Roman times", 15, QFont.Bold))  # 设置字体大小和加粗
        vbox.addWidget(Lab)

        self.CenterWidget = QWidget()
        centerHbox = QHBoxLayout()
        self.CenterWidget.setLayout(centerHbox)

        self.BottomWidget = QWidget()
        bottomHbox = QHBoxLayout()
        bottomHbox.setSpacing(20)
        self.BottomWidget.setLayout(bottomHbox)


        vbox.addWidget(self.CenterWidget)
        # vbox.addWidget(self.NextWidget)
        vbox.addWidget(self.BottomWidget)

        hboxLayout = QHBoxLayout()
        self.setLayout(hboxLayout)
        self.leftWidget = QWidget()
        self.leftWidget.setFixedWidth(120)
        self.leftWidget.setStyleSheet(
            "QWidget{ background:transparent;color: black;border: 0px solid white;}")
        # 设置布局
        leftWidgetLayout = QVBoxLayout()
        leftWidgetLayout.setSpacing(5)
        self.leftWidget.setLayout(leftWidgetLayout)
        label = ["账  户", "密  码", "安全码", "激活码"]

        lab4 = QLabel(label[2])
        lab4.setFixedHeight(40)
        lab4.setFixedWidth(100)
        lab4.setStyleSheet(
            "QWidget{ background:transparent;color: black;font-size:25px;border: 0px solid white;font-weight: bold;border-width: 0px;border-color: #141529;border-style: solid;border-radius:4;}")
        leftWidgetLayout.addWidget(lab4)

        lab3 = QLabel(label[0])
        lab3.setFixedHeight(40)
        lab3.setFixedWidth(100)
        lab3.setStyleSheet(
            "QWidget{ background:transparent;color: black;font-size:25px;border: 0px solid white;font-weight: bold;border-width: 0px;border-color: #141529;border-style: solid;border-radius:4;}")
        leftWidgetLayout.addWidget(lab3)

        lab1 = QLabel(label[1])
        lab1.setFixedHeight(40)
        lab1.setFixedWidth(100)
        lab1.setStyleSheet(
            "QWidget{ background:transparent;color: black;font-size:25px;border: 0px solid white;font-weight: bold;border-width: 0px;border-color: #141529;border-style: solid;border-radius:4;}")
        leftWidgetLayout.addWidget(lab1)

        lab2 = QLabel(label[3])
        lab2.setStyleSheet(
            "QWidget{ background:transparent;color: black;font-size:25px;border: 0px solid white;font-weight: bold;border-width: 0px;border-color: #141529;border-style: solid;border-radius:4;}")
        lab2.setFixedHeight(40)
        lab2.setFixedWidth(100)
        leftWidgetLayout.addWidget(lab2)

        Cancle_btn=QPushButton("取消")
        Cancle_btn.setFixedWidth(80)
        Cancle_btn.setStyleSheet(
            "QWidget{ background:#169bef;color: white;font-size:25px;border: 1px solid white;font-weight: bold;border-width: 0px;border-color: #141529;border-style: solid;border-radius:4;}")
        bottomHbox.addWidget(Cancle_btn)
        Cancle_btn.clicked.connect(self.Clicked)
        # 右布局

        self.RightWidget = QWidget()
        self.RightWidget.setFixedWidth(240)
        self.RightWidget.setStyleSheet(
            "QWidget{ background:transparent;color: black;border: 0px solid white;}")
        RightWidgetLayout = QVBoxLayout()
        RightWidgetLayout.setSpacing(5)
        self.RightWidget.setLayout(RightWidgetLayout)


        self.an_qm = QTextEdit()
        self.an_qm.setFixedHeight(40)
        self.an_qm.setFixedWidth(200)
        self.an_qm.setStyleSheet(
            "QWidget{ background:white;color: black;font-size:25px;border: 1px solid white;font-weight: bold;border-width: 1px;border-color: #141529;border-style: solid;border-radius:4;}")
        self.an_qm.setEnabled(True)
        RightWidgetLayout.addWidget(self.an_qm)


        self.user = QTextEdit()
        self.user.setFixedHeight(40)
        self.user.setFixedWidth(200)
        self.user.setStyleSheet(
            "QWidget{ background:white;color: black;font-size:25px;border: 1px solid white;font-weight: bold;border-width: 1px;border-color: #141529;border-style: solid;border-radius:4;}")
        self.user.setEnabled(True)
        RightWidgetLayout.addWidget(self.user)

        self.pwd = QLineEdit()
        self.pwd.setEchoMode(QLineEdit.Password)
        self.pwd.setFixedHeight(40)
        self.pwd.setFixedWidth(200)
        self.pwd.setStyleSheet(
            "QWidget{ background:white;color: black;font-size:25px;border: 1px solid white;font-weight: bold;border-width: 1px;border-color: #141529;border-style: solid;border-radius:4;}")
        self.pwd.setEnabled(True)
        RightWidgetLayout.addWidget(self.pwd)

        self.ji_hm = QLineEdit()

        self.ji_hm.setMaxLength(6)
        self.ji_hm.setFixedHeight(40)
        self.ji_hm.setFixedWidth(200)
        self.ji_hm.setStyleSheet(
            "QWidget{ background:white;color: black;font-size:25px;border: 1px solid white;font-weight: bold;border-width: 1px;border-color: #141529;border-style: solid;border-radius:4;}")
        self.ji_hm.setEnabled(True)
        RightWidgetLayout.addWidget(self.ji_hm)

        OK_btn = QPushButton("登录")
        OK_btn.setFixedWidth(80)
        OK_btn.setStyleSheet(
            "QWidget{ background:#169bef;color: white;font-size:25px;border: 1px solid white;font-weight: bold;border-width: 0px;border-color: #141529;border-style: solid;border-radius:4;}")

        bottomHbox.addWidget(OK_btn)
        OK_btn.clicked.connect(self.Clicked)
        centerHbox.addWidget(self.leftWidget)
        centerHbox.addWidget(self.RightWidget)

    def Clicked(self):
        try:
            who = self.sender()
            if who is not None:
                name = who.text()
                if name == "登录":
                    print('登入')
                    print(self.ji_hm.text())
                    print(self.pwd.text())
                    print(self.an_qm.toPlainText())
                    print(self.user.toPlainText())
                    self.password = self.pwd.text()  # 密码
                    self.user_name = self.user.toPlainText()  # 用户名
                    self.anQm = self.an_qm.toPlainText()  # 安全码
                    self.ji_hm_str = self.ji_hm.text()  # 激活码

                    self.Transactionmonitoring = TransactionDetial(self.anQm, self.user_name,self.password, self.ji_hm_str )  # 启动主业
                    self.close()
                    # self.CommitData()
                    # self.JudgeInfo()
                elif name =="取消":
                    self.ji_hm.clear()
                    self.pwd.clear()
                    self.an_qm.clear()
                    self.user.clear()

        except Exception as error:
            print(error)

class MyThread(threading.Thread):
    def __init__(self, n):
        super(MyThread, self).__init__()  # 重构run函数必须要写

    def run(self):
        print("ss")
def main():
    try:
        if hasattr(sys, '_MEIPASS'):
            os.chdir(sys._MEIPASS)
        app = QApplication(sys.argv)
        ex = LoginFrom()
        app.installEventFilter(ex)
        ex.show()
        sys.exit(app.exec_())
    except Exception as error:
        print(error)


if __name__ == '__main__':
   main()


